package com.lt.threadTest.simpleTest;

/**
 * 演示死锁
 */
public class DeadlockDemo {

    private String A = "A";
    private String B = "B";
    public static void main(String[] args) {
        new DeadlockDemo().deadLock();
    }

    /**
     * 演示死锁--调用A锁时沉睡两秒，然后调用B锁
     * 线程B调用B锁时调用A锁
     * 同时竞争线程B
     */
    public void deadLock(){
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (A){
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized(B){
                        System.out.println(1);
                    }
                }
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (B){
                    synchronized (A){
                        System.out.println(2);
                    }
                }
            }
        });
        thread1.start();
        thread2.start();
    }
}
